package czy.demo.common.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/* Date类型转换器 */
@Component
public class DateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String dateStr) {
        Date date = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        try {
            date = dateFormat.parse(dateStr);
        } catch (ParseException e) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                date = dateFormat.parse(dateStr);
            } catch (ParseException e1) {
                dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    date = dateFormat.parse(dateStr);
                } catch (ParseException e2) {
                    e2.printStackTrace();
                }
            }
        }
        return date;
    }

    public static void main(String[] args){
        System.out.println(new DateConverter().convert("2019-06-19 08:23:54").toLocaleString());
    }
}